package com.wsjj.yjh;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.LocalStreamEnvironment;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

//流处理
public class WordCountStreamDemo {
    public static void main(String[] args) {
//        1.环境准备
//        LocalStreamEnvironment env = StreamExecutionEnvironment.createLocalEnvironment();
        StreamExecutionEnvironment env = StreamExecutionEnvironment.createLocalEnvironmentWithWebUI(new Configuration());
//        2.读取文件
        DataStreamSource<String> source = env.readTextFile("input/flink.txt");
//        3.切割数据
        SingleOutputStreamOperator<Tuple2<String, Long>> flatMap = source.flatMap(new FlatMapFunction<String, Tuple2<String, Long>>() {
            public void flatMap(String value, Collector<Tuple2<String, Long>> out) throws Exception {
                String[] s = value.split(" ");
                for (String s1 : s) {
                    out.collect(Tuple2.of(s1, 1L));
                }
            }
        }).setParallelism(2);

//        4.聚合数据
        KeyedStream<Tuple2<String, Long>, String> keyBy = flatMap.keyBy(new KeySelector<Tuple2<String, Long>, String>() {
            public String getKey(Tuple2<String, Long> value) throws Exception {
                return value.f0;
            }
        });
        SingleOutputStreamOperator<Tuple2<String, Long>> sum = keyBy.sum(1);
//        5.输出数据
        sum.print();
//        6.执行
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
